<template>
  <a-drawer
    :title="title"
    width="90%"
    :visible="visible"
    @close="
      () => {
        this.visible = false
      }
    "
  >
    <a-form-model ref="form" :model="entity" :rules="rules" v-bind="layout">
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="客户名称">
            <Myuser disabled v-model="entity.CustomerName" />
          </a-form-model-item>
          <!-- <a-form-model-item label="单据类型" prop="BillType">
            <a-input v-model="entity.BillType" autocomplete="off" placeholder="单据类型" />
          </a-form-model-item> -->
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="业务员">
            <a-input disabled v-model="entity.Salesman" autocomplete="off" placeholder="业务员" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="单据号">
            <a-input disabled v-model="entity.DocumentNo" autocomplete="off" placeholder="系统自动生成" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <!-- <a-col :span="8">
          <a-form-model-item label="收发类别" prop="SendReceiveType">
            <a-input v-model="entity.SendReceiveType" autocomplete="off" placeholder="收发类别" />
          </a-form-model-item>
        </a-col> -->
        <a-col :span="8">
          <a-form-model-item label="联系人" prop="Contacts">
            <!-- <a-input v-model="entity.Contacts" autocomplete="off" placeholder="联系人" /> -->
            <a-select v-model="entity.Contacts" placeholder="客户联系人" @change="Contacts($event)">
              <a-select-option v-for="(item, dei) in List" :key="item.dei" :value="item.Tel_Code">
                {{ item.Name }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
          <!-- Tel_Code -->
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="联系人电话">
            <a-input disabled v-model="entity.LinkManTel" autocomplete="off" placeholder="联系人电话" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="收货人" prop="ConsigneeName">
            <a-input v-model="entity.ConsigneeName" autocomplete="off" placeholder="收货人" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <!-- <a-col :span="8">
          <a-form-model-item label="单据日期" prop="DocumDate">
            <a-input v-model="entity.DocumDate" autocomplete="off" placeholder="单据日期" />
          </a-form-model-item>
        </a-col> -->
        <a-col :span="8">
          <a-form-model-item label="单据日期">
            <a-date-picker format="YYYY-MM-DD" style="width: 100%" v-model="entity.DocumDate" />
          </a-form-model-item>
        </a-col>
        <!-- <a-col :span="8">
          <a-form-model-item label="销售发票号" prop="SalInvNo">
            <a-input v-model="entity.SalInvNo" autocomplete="off" placeholder="销售发票号" />
          </a-form-model-item>
        </a-col> -->

        <a-col :span="8">
          <a-form-model-item label="发运方式">
            <a-select v-model="entity.ShipVia" style="width: 100%" placeholder="发运方式">
              <a-select-option v-for="item in shipvia" :key="item.Id" :value="item.DicName">
                {{ item.DicName }}
              </a-select-option>
            </a-select>
            <!-- <a-input v-model="entity.ShipVia" autocomplete="off" placeholder="发运方式" /> -->
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="收货地址" prop="Address">
            <a-textarea v-model="entity.Address" autocomplete="off" placeholder="发往地址" />
          </a-form-model-item>
        </a-col>
      </a-row>

      <!-- <a-col :span="8">
      <a-row>
      </a-row>
          <a-form-model-item label="操作人" prop="Operator">
            <a-input v-model="entity.Operator" autocomplete="off" placeholder="操作人" />
          </a-form-model-item>
        </a-col> -->

      <!-- <a-form-model-item label="开票名称" prop="BillingName">
          <a-input v-model="entity.BillingName" autocomplete="off" placeholder="开票名称" />
        </a-form-model-item> -->
    </a-form-model>
    <MaterialChoose ref="materialChoose" @onChoose="handleChoose"></MaterialChoose>
    <a-table
      ref="table"
      :scroll="{ y: 530 }"
      :columns="columns"
      :rowKey="(row, index) => row.Id"
      :dataSource="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :bordered="true"
      size="small"
    >
      <template slot="cInvName" slot-scope="text, record">
        <span>{{ record.ProductId }}/{{ record.cInvName }}</span>
      </template>
      <span slot="CreateTime" slot-scope="CreateTime">{{ timeFormat(CreateTime) }}</span>
      <span slot="action" slot-scope="text, record, index">
        <template>
          <a @click="handleDelete([record.Id], index)">删除</a>
        </template>
      </span>
      <!-- 发货数量 -->
      <template slot="Quantity" slot-scope="text, record">
        <a-input
          size="small"
          class="input"
          type="number"
          style="text-align: right;"
          @change="QuantityChange(record, index)"
          v-model="record.Quantity"
        ></a-input>
      </template>
      <!-- 辅助发货数量 -->
      <template slot="AuxiliaryQuantity" slot-scope="text, record">
        <a-input
          size="small"
          class="input"
          style="text-align: right;"
          type="number"
          v-model="record.AuxiliaryQuantity"
        ></a-input>
      </template>
      <!-- 批次号 -->
      <template slot="Batch" slot-scope="text, record">
        <a-input size="small" class="input" style="text-align: right;" type="number" v-model="record.Batch"></a-input>
      </template>
      <!-- 无税单价 -->
      <template slot="NoTaxPrice" slot-scope="text, record">
        <a-input size="small" class="input" type="number" v-model="record.NoTaxPrice"></a-input>
      </template>
      <!-- 含税单价 -->
      <template slot="TaxPrice" slot-scope="text, record">
        <a-input size="small" class="input" type="number" v-model="record.TaxPrice"></a-input>
      </template>
      <!-- 无税金额 -->
      <template slot="NoTaxMoney" slot-scope="text, record">
        <a-input size="small" class="input" type="number" v-model="record.NoTaxMoney"></a-input>
      </template>
      <!-- 税额 -->
      <template slot="TaxMoney" slot-scope="text, record">
        <a-input size="small" class="input" type="number" v-model="record.TaxMoney"></a-input>
      </template>
      <!-- 价税合计 -->
      <template slot="PriceTaxTotal" slot-scope="text, record">
        <a-input size="small" class="input" type="number" v-model="record.PriceTaxTotal"></a-input>
      </template>
      <!-- 折扣 -->
      <template slot="Discount" slot-scope="text, record">
        <a-input size="small" class="input" type="number" v-model="record.Discount"></a-input>
      </template>
      <!-- 折扣无税单 -->
      <template slot="DisNoTaxPrice" slot-scope="text, record">
        <a-input size="small" class="input" type="number" v-model="record.DisNoTaxPrice"></a-input>
      </template>
      <!-- 折扣无税金额 -->
      <template slot="DisNoTaxMoney" slot-scope="text, record">
        <a-input size="small" class="input" type="number" v-model="record.DisNoTaxMoney"></a-input>
      </template>
      <!-- 折扣税额 -->
      <template slot="DisTaxMoney" slot-scope="text, record">
        <a-input size="small" class="input" type="number" v-model="record.DisTaxMoney"></a-input>
      </template>
      <!-- 折扣价税合计 -->
      <template slot="DisPriceTaxTotal" slot-scope="text, record">
        <a-input size="small" class="input" type="number" v-model="record.DisPriceTaxTotal"></a-input>
      </template>
    </a-table>
    <div
      :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '4px 16px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 1
      }"
    >
      <a-button type="primary" @click="addTable">添加</a-button>&nbsp; <a-button @click="close">取消</a-button>&nbsp;
      <a-button type="primary" @click="handleSubmit">保存</a-button>
    </div>
  </a-drawer>
</template>

<script>
import OperatorCache from '@/utils/cache/OperatorCache'
import moment from 'moment'
import Myuser from '@/components/MyuserCloose/List.vue'
import MaterialChoose from '@/components/MaterialChoose/PriceMaterialChooseCopy1.vue'
const columns = [
  { title: '品名', dataIndex: 'cInvName', scopedSlots: { customRender: 'cInvName' } },

  { title: '规格型号', dataIndex: 'cInvStd' },
  { title: '业务类型', dataIndex: 'OddType' },
  { title: '待发数量', dataIndex: 'LastBalance' },

  { title: '发货数量', dataIndex: 'Quantity', scopedSlots: { customRender: 'Quantity' } },
  // {
  //   title: '辅助发货数量',
  //   dataIndex: 'AuxiliaryQuantity',
  //   align: 'right',
  //   scopedSlots: { customRender: 'AuxiliaryQuantity' }
  // },
  // { title: '批次', dataIndex: 'Batch', align: 'right', scopedSlots: { customRender: 'Batch' } },
  // { title: '报价', dataIndex: 'Offer', scopedSlots: { customRender: 'Offer' } },
  // { title: '无税单价', dataIndex: 'NoTaxPrice', scopedSlots: { customRender: 'NoTaxPrice' } },
  // { title: '含税单价', dataIndex: 'TaxPrice', scopedSlots: { customRender: 'TaxPrice' } },
  // { title: '无税金额', dataIndex: 'NoTaxMoney', scopedSlots: { customRender: 'NoTaxMoney' } },
  // { title: '税额', dataIndex: 'TaxMoney', scopedSlots: { customRender: 'TaxMoney' } },
  // { title: '价税合计', dataIndex: 'PriceTaxTotal', scopedSlots: { customRender: 'PriceTaxTotal' } },
  // { title: '折扣', dataIndex: 'Discount', scopedSlots: { customRender: 'Discount' } },
  // {
  //   title: '折扣无税单价',
  //   dataIndex: 'DisNoTaxPrice',
  //   align: 'center',
  //   scopedSlots: { customRender: 'DisNoTaxPrice' }
  // },
  // {
  //   title: '折扣无税金额',
  //   dataIndex: 'DisNoTaxMoney',
  //   align: 'center',
  //   scopedSlots: { customRender: 'DisNoTaxMoney' }
  // },
  // { title: '折扣税额', dataIndex: 'DisTaxMoney', scopedSlots: { customRender: 'DisTaxMoney' } },
  // {
  //   title: '折扣价税合计',
  //   dataIndex: 'DisPriceTaxTotal',
  //   align: 'center',
  //   scopedSlots: { customRender: 'DisPriceTaxTotal' }
  // },
  // { title: '批次', dataIndex: 'Batch', scopedSlots: { customRender: 'action' } },

  // { title: '产品Id', dataIndex: 'ProductId' },

  { title: '操作', dataIndex: 'action', align: 'left', scopedSlots: { customRender: 'action' } }
]
export default {
  watch: {
    data: {
      handler(n, o) {
        //console.log(n)
        n.forEach(item => {
          if (Number(item.Quantity) < 0) {
            this.$set(item, 'Quantity', 1)
            this.$message.warning('数量不能小于0')
            return
          }
        })
      },
      deep: true,
      immediate: true
    }
  },
  components: {
    MaterialChoose,
    Myuser
  },
  props: {
    parentObj: Object
  },
  data() {
    return {
      Sales: [],
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true,
        onShowSizeChange: (current, pageSize) => {
          this.pageSize = pageSize
        }
      },
      Did: '',
      cc: false,
      shipvia: [],
      Dname: '',
      Id: '',
      selectedRowKeys: [],
      List: [], //联系人列表
      filters: {},
      sorter: { field: 'Id', order: 'desc' },
      columns,
      data: [],
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 }
      },
      visible: false,
      loading: false,
      entity: {},
      rules: {
        Object: [{ required: true, message: '未输入', trigger: 'blur' }],
        OddNumbers: [{ required: true, message: '未输入', trigger: 'blur' }],
        SalesType: [{ required: true, message: '未输入', trigger: 'blur' }],
        Salesman: [{ required: true, message: '未输入', trigger: 'blur' }],
        LinkManTel: [{ required: true, message: '未输入', trigger: 'blur' }],
        Address: [{ required: true, message: '未输入', trigger: 'blur' }],

        ConsigneeName: [{ required: true, message: '未输入', trigger: 'blur' }]
      },
      title: ''
    }
  },
  created() {
    this.getSalesType()
    this.getshipvia()
  },
  methods: {
    QuantityChange(row, i) {
      if (row.Quantity > row.LastBalance) {
        this.$message.warning('发货数量不能超过待发数量')
        this.$set(row, 'Quantity', row.LastBalance)
      }
    },
    Contacts(value) {
      this.entity.LinkManTel = value
    },

    op() {
      return OperatorCache.info
    },
    handleDelete(ids, index) {
      var thisObj = this
      if (ids[0]) {
        this.$confirm('确认删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return new Promise((resolve, reject) => {
            thisObj.$http.post('/DeliveryManagement/DEL_DeliveryNoticeDetails/DeleteData', ids).then(resJson => {
              resolve()

              if (resJson.Success) {
                thisObj.$message.success('操作成功!')

                thisObj.getDataList()
              } else {
                thisObj.$message.error(resJson.Msg)
              }
            })
          })
        })
      } else {
        this.data.splice(index, 1)
      }
    },
    getshipvia() {
      this.$http
        .post('/Base_BasicData/Base_DictionaryMain/GetTheDataByDicKey', {
          Condition: 'DicKey',
          Keyword: 'shipvia'
        })
        .then(res => {
          //console.log(res)
          if (res.Data.DictionaryDetailsList) this.shipvia = res.Data.DictionaryDetailsList
        })
    },
    getSalesType() {
      this.$http
        .post('/Base_BasicData/Base_DictionaryMain/GetTheDataByDicKey', {
          Condition: 'DicKey',
          Keyword: 'Salestype'
        })
        .then(res => {
          //console.log(res)
          if (res.Data.DictionaryDetailsList) this.Sales = res.Data.DictionaryDetailsList
        })
    },

    handleChoose(a) {
      a.forEach(item => {
        this.data.push({
          ProductId: item.cInvCode,
          cInvName: item.cInvName,
          cInvStd: item.cInvStd,
          OddType: item.OddType,
          OddNumbers: item.OddNumbers,
          Quantity: item.Quantity,
          LastBalance: item.Quantity
        })
      })
    },
    addTable() {
      this.$refs.materialChoose.openChoose(this.entity.CustomerId, this.data)
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }

      // this.getDataList()
    },
    close() {
      this.visible = false

      this.entity = {}
      this.data = []
    },
    init() {
      this.visible = true
      this.entity = {}

      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    openForm(item, title, Did, Dname) {
      this.init()

      this.cCusName = item.cCusName
      this.entity = item
      this.entity.DocumDate = moment(new Date())
      this.$set(this.entity, 'Salesman', item.AllocationName)
      this.entity.CustomerName = item.cCusName
      this.entity.CustomerId = item.Id || item.cCusCode
      this.$http
        .post('/CustomerManagement/Cust_CustomerLinkMan/GetDataListByConditions', {
          Search: [
            {
              Condition: 'CustomerId',
              Keyword: item.cCusCode
            }
          ],
          ...this.filters
        })
        .then(resJson => {
          this.loading = false
          this.List = resJson.Data
        })
      this.title = title
    },
    handleSubmit() {
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        this.loading = true

        var entityData = { ...this.entity }

        var DDND_List = [...this.data]
        this.DDND_List = DDND_List
        //console.log(this.DDND_List)
        entityData.DDND_List = this.DDND_List
        this.$http.post('/DeliveryManagement/DEL_DeliveryNoticeMain/SaveData', entityData).then(resJson => {
          this.loading = false

          if (resJson.Success) {
            this.$message.success('操作成功!')
            this.visible = false

            if (this.parentObj.user == 1) {
              this.parentObj.getDataList()
            } else {
              this.parentObj.getuserList()
            }
          } else {
            this.$message.error(resJson.Msg)
          }
        })
      })
    }
  }
}
</script>
